# -*- coding: utf-8 -*-
from flask import Flask, Response, render_template, request
from flask.sessions import NullSession

import camera
import servo

app = Flask(__name__)

video_task = camera.Video_task(0, 480, 640)

servo_task = servo.Servo_task(13, 2500, 50)


@app.route('/')  # 主页
def index():
    # jinja2模板，具体格式保存在index.html文件中
    return render_template('index.html')


@app.route('/video_feed/')  # 这个地址返回视频流响应
def video_feed():
    video_task.num += 1
    return Response(video_task.video_feed(), mimetype='multipart/x-mixed-replace; boundary=frame')


@app.route('/get_button/', methods=['GET'])
def get_button():
    if request.method == 'GET':
        button_num = request.args.get('num')
        if button_num == 1:
            # 将舵机目标值设置为1000(0~4096)
            servo_task.set_position(1000)
    else:
        print("not ok")
    return "ok"


@app.route('/get_switch/', methods=['GET'])
def get_switch():
    if request.method == 'GET':
        switch_num = request.args.get('num')
        switch_state = request.args.get('state')

        if switch_num == "1":
            camera_control(switch_state)
        
        if switch_num == "3":
            servo_control(switch_state)

        print(switch_num + switch_state)
    return "ok"


@app.route('/get_gamepad/', methods=['GET'])
def get_gamepad():
    if request.method == 'GET':
        l_x = float(request.args.get('l_x'))
        l_y = float(request.args.get('l_y'))
        r_x = float(request.args.get('r_x'))
        r_y = float(request.args.get('r_y'))
        # button_0 = int(request.args.get('button_0'))
        # button_1 = int(request.args.get('button_1'))
        # button_2 = int(request.args.get('button_2'))
        # button_3 = int(request.args.get('button_3'))
    return "ok"


def camera_control(state):
    if state == "true":
        video_task.open_cam = True
    if state == "false":
        video_task.open_cam = False
        

def servo_control(state):
    if state == "true":
        servo_task.open_servo = True
    if state == "false":
        servo_task.open_servo = False


if __name__ == '__main__':
    video_task.start()
    servo_task.start()

    app.run(host="0.0.0.0", port=5000, debug=False)

    video_task.join()
    servo_task.join()
